import { Context } from 'koa';
import UserModel from '../dbs/models/users'

class UserController {

  constructor() {
    this.listUsers = this.listUsers.bind(this)
    this.updateUser = this.updateUser.bind(this)
    this.showUserDetail = this.showUserDetail.bind(this)
    this.deleteUser = this.deleteUser.bind(this)
    this.queryUser = this.queryUser.bind(this)
  }

  async listUsers(ctx) {
    ctx.body = 'ListUsers controller'
  }

  async showUserDetail(ctx) {
    ctx.body = `ShowUserDetail controller with ID=${ctx.params.id}`
  }

  async deleteUser(ctx) {
    ctx.body = `DeleteUser controller with ID=${ctx.params.id}`
  }

  async updateUser(ctx) {
    const { email, uid, age, sex, phone, nickname } = ctx.request.body;
    const regPhone = /^1([38][0-9]|4[579]|5[0-9]|6[6]|7[0135678]|9[189])\d{8}$/
    if (!uid || !email) {
      ctx.body = {
        code: 40001,
        message: '参数缺失',
        data: null
      }
    } else if (!nickname || nickname.length < 0 || nickname.length > 100) {
      ctx.body = {
        code: 40001,
        message: '昵称格式错误',
        data: null
      }
    } else if (!phone || !regPhone.test(phone)) {
      ctx.body = {
        code: 40001,
        message: '手机号码格式错误',
        data: null
      }
    } else if (!age || !sex) {
      ctx.body = {
        code: 40001,
        message: '参数缺失',
        data: null
      }
    } else {
      const admin = await UserModel.Users.update({uid}, {
        age,
        sex,
        phone,
        nickname
      }, (err, tank) => {
        if (err) {
          ctx.body = {
            code: 40003,
            message: '当前用户不存在',
            data: null
          }
        }
        console.log(tank)
        ctx.body = {
          code: 20000,
          message: '保存成功',
          data: null
        }
      })
    }
  }

  async queryUser(ctx) {
    const { uid } = ctx.params
    if (!uid) {
      ctx.body = {
        code: 40001,
        message: '参数缺失',
        data: null
      }
    }
    const userinfo = await UserModel.Users.find({ uid });
    if (!userinfo) {
      ctx.body = {
        code: 40003,
        message: '用户不存在',
        data: null
      }
    }
    ctx.body = {
      code: 20000,
      message: '查询成功',
      data: userinfo[0]
    }
  }

}

export default new UserController()